﻿// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
// PARTICULAR PURPOSE.
//
// Copyright (c) 2007 Microsoft Corporation. All rights reserved.

using Microsoft.Office.Interop.Word;
using Microsoft.Office.Tools;

namespace TShooter.TfsWord.AddIn.UIManager.Word
{
    /// <summary>
    /// Provides UI elements relationship management for VSTO Word extensions.
    /// </summary>
    public sealed class UIManager : UIManagerBase<UIContainer, Window>
    {
        #region Fields

        private readonly Application application;
        private int lastWindowCount;

        #endregion

        #region .ctor

        public UIManager(CustomTaskPaneCollection customTaskPanes, Application application)
            : base(customTaskPanes)
        {
            this.application = application;

            //capture the necessary app events
            this.application.DocumentChange += app_DocumentChange;
            this.application.WindowActivate += app_WindowActivate;
        }

        #endregion

        #region Event Handlers

        private void app_DocumentChange()
        {
            RemoveOrphanedWindows();
        }

        private void app_WindowActivate(Document doc, Window win)
        {
            RemoveOrphanedWindows();
        }

        #endregion

        #region Methods

        internal override UIContainer CreateContainer(Window window)
        {
            return new UIContainer(window, this);
        }

        private void RemoveOrphanedWindows()
        {
            int newWindowCount = application.Windows.Count;

            if (newWindowCount < lastWindowCount) // at least one window has been closed.
            {
                // go through the UIContainers to find out whose window is no longer in Application.Windows collection
                // then remove the orphaned UIContainer from the collection
                for (int i = UIContainers.Count - 1; i >= 0; i--)
                {
                    bool found = false;

                    foreach (Window wnd in application.Windows)
                    {
                        if (wnd == UIContainers[i].Window)
                        {
                            found = true;
                            break;
                        }
                    }

                    if (!found)
                    {
                        UIContainers.RemoveAt(i);
                    }
                }
            }

            lastWindowCount = newWindowCount;
        }

        #endregion
    }
}